

export interface ErrorMessage {
  message: string
  stack: Array<{
    line: number
    column: number
    filename: string
  }>
}

function chromeParser(splitRes: string[],err:Error):ErrorMessage{
  const  stack :ErrorMessage['stack']= []
  const reg =  /(.*) (.*):(\d+):(\d+)$/
  for(let i = 1 ; i <splitRes.length;i++){
    const match = splitRes[i].match(reg)
    if(match&&match[2]!=="<anonymous>"){
      stack.push({
        line: parseInt(match[3]),
        column:parseInt(match[4]),
        filename:match[2]
      })
    }
  }
  return {
    message:err.message,
    stack
  }
}
function firefoxParser(splitRes:string[],err:Error): ErrorMessage{
  const  stack :ErrorMessage['stack']= []
  const reg = /(\w+@)?(.*):(\d+):(\d+)$/
  for(let i = 1 ; i <splitRes.length;i++){
    const s =  splitRes[i].replace(/\s/g,'')
    const match = s.match(reg)
    if(match&&match[2]!=="<anonymous>"){
      stack.push({
        line: parseInt(match[3]),
        column:parseInt(match[4]),
        filename:match[2]
      })
    }
  }
  return {
    message:err.message,
    stack
  }
}


function isChrome(str:string):0|1{
  const testReg =  /(.*) (.*):(\d+):(\d+)$/
  const res = str.match(testReg)
  if(res){
    return 1
  }else{
    return 0
  }
}


export function parseError(err: Error): ErrorMessage {
  const emptyMessage = {
    message:err.message,
    stack:[]
  }
  if(err.stack){
    const splitRes = err.stack.split(/[(\r\n)\r\n]+/)
    if(splitRes.length > 1){
      const sign = isChrome(splitRes[1])
      switch(sign){
        case 0:
          return firefoxParser(splitRes,err)
        case 1:
          return  chromeParser(splitRes,err)
        default:
          return emptyMessage
      }
    }else{
      return emptyMessage
    }
  }else{
    return emptyMessage
  }
}